<template>
  <view class="login">
    <view class="logo">
      <image
          src="/static/login/logo.png"
      ></image>
    </view>

    <text class="txt">欢迎登录</text>

    <view style="margin-top: 40rpx;">
      <van-field
          :value="PhoneOrGFAccount"
          @input="updateGF_ACCOUNT"
          placeholder="GF账号/手机号"
      />
      <view style="height:10rpx;"></view>
      <van-field
          v-if="isPasswordLogin"
          :value="Pwd"
          placeholder="密码"
          @input="updatePassword"
          :type="isPasswordVisible ? 'text' : 'password'"
          :right-icon="isPasswordVisible ? '/static/login/visible.png' : '/static/login/invisible.png'"
          @click-icon="togglePasswordVisibility"
      />
      <van-field
          v-else
          :value="sms_code"
          @input="updateSmsCode"
          placeholder="短信验证码"
      ><van-button slot="button" size="small" type="default" @click="requestVerificationCode">验证码</van-button>
      </van-field>
    </view>

    <view class="policy">
      <van-checkbox :value="checked" @change="onChange" style="font-size: 32rpx;">已阅读并同意</van-checkbox>
      <text @click="show('agreement')" class="icon">《服务协议》</text>
      <text style="margin-top:8rpx;font-size: 32rpx;color: black;">和</text>
      <text @click="show('agreement')" class="icon">《隐私协议》</text>
    </view>

    <button class="button" :style="{ backgroundColor: buttonColor }" @click="Login_phone">
      登录
    </button>

    <view class="extra">
      <view class="caption">
        <text>其他登录方式</text>
      </view>

      <view class="nav">
        <view class="item" style="width:25%">
          <image @click="Third_login(1438)"  mode="heightFix" src="/static/login/QQ.png" role="img"></image>
        </view>

        <view class="item" style="width:25%">
          <image @click="WeiXin_Login()"  mode="heightFix" src="/static/login/WX.png" role="img"></image>
        </view>

        <view class="item" style="width:25%">
          <image @click="Third_login(1440)"  mode="heightFix" src="/static/login/WB.png" role="img"></image>
        </view>

        <view class="item" style="width:25%">
          <image @click="Third_login(1441)"  mode="heightFix" src="/static/login/PAY.png" role="img"></image>
        </view>
      </view>
    </view>
    <view>
      <button @click="Apple_Login()" class="apple_button" style="border: 1px solid #c8c8c8; border-radius: 6px;">
        <image class="apple_img" src="/static/login/apple.png"></image>
        通过apple登录
      </button>
    </view>

    <view style="position:absolute; left: 50%; transform: translateX(-50%);justify-content:center;align-items:center;bottom:40rpx;width:450rpx;">
      <view style="color:#6a6a6a;font-size: 28rpx;">
        <text @click="toggleLoginMethod" >
          {{ isPasswordLogin ? '短信验证登录' : '密码登录' }}
        </text>
        <text style="margin:0 10rpx;">|</text>
        <text @click="navigateToRegister" >用户注册</text>
        <text style="margin:0 10rpx;">|</text>
        <text @click="navigateToForgetPassword">忘记密码</text>
      </view>
    </view>

  </view>
</template>

<script setup>
import { computed, onBeforeMount, onMounted, ref, toRaw, watch} from 'vue';
import decLoginApi from '/api/dec/decUser/decLoginApi';
import decRegisterApi from '/api/dec/decUser/decRegisterApi';
import decUtilsApi from '/api/dec/decUtilsApi';
import cryptoUtils from '@/utils/CryptoJS';

// 全局状态globalData
import { storeToRefs } from "pinia";
import { useGlobalDataStore } from "@/globalData.js"
const { globalData } = storeToRefs(useGlobalDataStore());
const { logIn } = useGlobalDataStore();

const navigateToRegister = () => {
  uni.navigateTo({
    url: '/pages/login/register'
  })
}

const navigateToForgetPassword = () => {
  uni.navigateTo({
    url: '/pages/login/forgetPassword'
  })
}

// 登录凭证
const authData = '';

const PhoneOrGFAccount = ref('');
const Pwd = ref('');
const sms_code = ref('');
const isPasswordLogin = ref(true);

const visit_data = ref();
const system_info = ref();
const encrypted_pwd_info = ref();
const checked = ref(false);
const isPasswordVisible = ref(true);

const buttonColor = computed(() => {
  if ( PhoneOrGFAccount.value && (sms_code.value || Pwd.value) && checked.value) {
    return '#ffaa00'
  } else {
    return '#e2e2e2'
  }
})

const togglePasswordVisibility = () => {
  isPasswordVisible.value = !isPasswordVisible.value;
};
function onChange() {
  checked.value = !checked.value;
}
function updateGF_ACCOUNT(event) {
  PhoneOrGFAccount.value = event.detail;
}
function updatePassword(event) {
  Pwd.value = event.detail;
}
function updateSmsCode(event) {
  sms_code.value = event.detail;
}
function toggleLoginMethod() {
  isPasswordLogin.value = !isPasswordLogin.value;
}

/**
 * 发送验证码
 * @param phone_num
 * @constructor
 */
function Send_sms(phone_num) {
  console.log("phone_num",phone_num);
  if (!phone_num) {
    console.error("手机号为空，请检查");
    return;
  }
  const ts = Date.now().toString();
  let params = {
    mob_code: '86',
    mob: phone_num,
    type: '2',
    client_type: system_info.value.device_type,
    time: ts,
  }
  decUtilsApi.Send_sms_API(params).then((res) => {
    console.log('Send_sms_API成功，', res)
  }).catch((err) => {
    console.error('Send_sms_API失败，', err)
  })
}

/**
 * 隐私协议
 * @param page
 */
function show(page) {
  uni.navigateTo({
    url: `/pages/login/policy?page=${page}`
  });
}

/**
 * 初始化数据
 * @returns {Promise<void>}
 * @constructor
 */
async function Loading_data() {
  visit_data.value = globalData.value.VISIT_DATA;
  system_info.value = globalData.value.SYSTEM_INFO;
  encrypted_pwd_info.value = globalData.value.ENCRYPTED_PWD_INFO;
}

/**
 * 发送验证码
 * @returns {Promise<void>}
 */
async function requestVerificationCode() {
  Send_sms(PhoneOrGFAccount.value)
}

/**
 * 手机号/GF帐号+密码登录
 * @returns {Promise<void>}
 * @constructor
 */
async function Login_phone() {
  if(buttonColor.value !== '#ffaa00') {
    console.log('表单为空');
    return;
  }
  uni.showLoading({
  	title: '加载中'
  });
  
  let ts = Date.now().toString();
  const EncryptPwd = cryptoUtils.MD5Encrypt(Pwd.value);
  const EncryptDysign = cryptoUtils.MD5Encrypt('login_phone' + PhoneOrGFAccount.value + ts + EncryptPwd);

  let params = {
    name: PhoneOrGFAccount.value,// 用户账号
    dysign: EncryptDysign,// 动态签名（action值+name+ts+登录密码MD5（login334682...）拼接后MD5加密，确保密码不披露）
    login_ts: ts,//时间戳
    device_type: system_info.value.device_type,//客户端登录设备类型
    client_version: 'ddwx_app',//移动端版本号
    device_code: system_info.value.device_code,//登录设备名称（iPhone 7 Plus）（仅device_type=7网页登录不需要传入 ）
    device_uuid: system_info.value.device_uuid,//登录设备id（仅device_type=7网页登录不需要传入）
  };

  console.log('Login_phone_API 参数',params);

  try{
    const res = await decLoginApi.Login_phone_API(params);
    //console.log('Login_phone_API成功，', res);
    // console.log('Login_phone_API type ',Object.prototype.toString.call(res));
    let rdata=res;
    if(typeof res === 'string'){
      rdata = JSON.parse(res);
    }
    if(!rdata.error && rdata.error === 0){
      if(rdata.gf_datas == null){
        if(typeof rdata.datas === 'string') {
          const resDatas = rdata.datas;
          const key = EncryptPwd.slice(-16);
          const iv = EncryptPwd.slice(0,16);
          const DecryptDatas = cryptoUtils.AES_Decrypt(resDatas, key, iv);
          // console.log('Login_phone_API DecryptDatas ',Object.prototype.toString.call(DecryptDatas),DecryptDatas);
          if(typeof DecryptDatas === 'string'){
            logIn(JSON.parse(DecryptDatas));
            uni.switchTab({
              url: "/pages/index/index"
            });
			uni.hideLoading();
			uni.showToast({
				title: '登录成功',
				duration: 2000
			});
            console.log('登录成功，');
          }
        }
      }else{
        //手机号绑定多个帐号时选择登录的帐号
      }
    }
  } catch(err) {
    console.error('Login_phone_API失败，', err);
  }
}

/**
 * 第三方授权登录
 * @param third_type
 * @param authData
 * @constructor
 */
function Third_login(third_type, authData) {
	uni.showLoading({
		title: '加载中'
	});
	
  let ts = Date.now().toString();
  const EncryptPwd = cryptoUtils.MD5Encrypt(ts);
  let params = {
    third_type: third_type, // 1438-QQ授权,1439-微信授权,1440-新浪微博授权,1441-支付宝授权
    third_user_id: '', // QQ openId,微信unionid，微博 uid,支付宝user_id（仅微信授权传入auth_code时可不传）
    openid: '', // 微信普通用户的标识，对当前开发者帐号唯一（仅微信授权传入auth_code时可不传）
    access_token: '', // 接口调用凭证 (QQ、微信、微博的access_token，支付宝授权码 code)（仅微信授权传入auth_code时可不传）
    auth_code: '', // 仅微信授权时必填，微信授权码 code(使用auth_code获取third_user_id,openid,access_token)
    device_type: system_info.value.device_type, // 客户端登录设备类型
    aes_key: EncryptPwd, // AES公钥，登录返回data经过该密钥加密

    // after is optional
    client_version: 'ddwx_app',//移动端版本号
    device_code: system_info.value.device_code,//登录设备名称（iPhone 7 Plus）（仅device_type=7网页登录不需要传入 ）
    device_uuid: system_info.value.device_uuid,//登录设备id（仅device_type=7网页登录不需要传入）
  }
  // 根据不同的第三方登录类型，设置相应的参数
  switch (third_type) {
    case 1438: // QQ 授权
      params.third_user_id = authData.openId;
      params.access_token = authData.accessToken;
      break;
    case 1439: // 微信授权
      params.auth_code = authData.code;
      break;
    case 1440: // 新浪微博授权
      params.third_user_id = authData.uid;
      params.access_token = authData.accessToken;
      break;
    case 1441: // 支付宝授权
      params.access_token = authData.code;
      break;
    case 1442: // 苹果登录
      params.access_token = authData.accessToken;
      params.third_user_id = authData.userId;
      break;
    default:
      console.error('不支持的第三方登录类型');
      return;
  }

  decLoginApi.Third_login_API(params).then((res) => {
    console.log('Third_login_API成功，res: ', res);
    let rdata = res;
    if(typeof res === 'string'){
      rdata = JSON.parse(res);
    }
    if(!rdata.error && rdata.error === 0){
      if(rdata.gf_datas == null){
        if(typeof rdata.datas === 'string') {
          const resDatas = rdata.datas;
          const key = EncryptPwd.slice(-16);
          const iv = EncryptPwd.slice(0,16);
          const DecryptDatas = cryptoUtils.AES_Decrypt(resDatas, key, iv);
          // console.log('Login_phone_API DecryptDatas ',Object.prototype.toString.call(DecryptDatas),DecryptDatas);
          if(typeof DecryptDatas === 'string'){
            logIn(JSON.parse(DecryptDatas));
            uni.switchTab({
              url: "/pages/index/index"
            });
			uni.hideLoading();
			uni.showToast({
				title: '登录成功',
				duration: 2000
			});
            console.log('登录成功，');
          }
        }
      }else{
        //手机号绑定多个帐号时选择登录的帐号
      }
    }

  }).catch((err) => {
    console.error('Third_login_API失败，', err);
  })
}

/**
 * 苹果登录 Sign with Apple
 * @constructor
 */
function Apple_Login() {
  // 检查当前环境是否支持苹果登录
  uni.getProvider({
    service: 'oauth',
    success: (res) => {
      if (res.provider.includes('apple')) {
        uni.login({
          provider: 'apple',
          success: (loginRes) => {
            // 获取用户信息
            uni.getUserInfo({
              provider: 'apple',
              success: (info) => {
                console.log('uni.getUserInfo 的 res: ', info);
                const authData = {
                  code: loginRes.code,
                  ...info.authResult
                };
                // TODO 这里需要检查Apple的第三方类型
                const appleThirdType = 1442; // 苹果登录的第三方类型
                // 调用第三方登录函数
                Third_login(appleThirdType, authData);
              },
              fail: (err) => {
                console.error('获取苹果用户信息失败:', err);
              }
            });
          },
          fail: (err) => {
            console.error('苹果登录授权失败:', err);
          }
        });
      } else {
        console.error('当前设备不支持苹果登录');
      }
    },
    fail: (err) => {
      console.error('获取第三方登录提供商失败:', err);
    }
  });
}

/**
 * 微信登陆
 * @constructor
 */
function WeiXin_Login() {
  uni.getProvider({
    service: 'oauth',
    success: (res) => {
      if (res.provider.includes('weixin')) {
        uni.login({
          provider: 'weixin',
          onlyAuthorize: true, // 仅请求授权认证
          success: (event) => {
            console.log('微信登陆的res： ',event)
            const { code } = event;
            const weixinThirdType = 1439; // 微信登录的第三方类型
            const authData = {
              code: code,
              ...event
            };
            Third_login(weixinThirdType, authData);
          },
          fail: (err) => {
            console.error('微信登录授权失败:', err);
          }
        });
      }
    },
    fail: (err) => {
      console.error('获取第三方登录提供商失败:', err);
    }
  })
}

/**
 * 检查GF帐号
 * @param gfid
 * @constructor
 */
function Check_gfaccount(gfid) {
  if(!gfid) {
    console.error("Check_gfaccount参数为空，请检查");
    return;
  }
  let params = {
    action: 'check_gfaccount',
    gfid: gfid,
  }
}

async function init(){
  await Loading_data();
  // await Login_phone(PhoneOrGFAccount.value, Pwd.value);
}

onMounted(()=> {
  init();
  // const res = uni.login();
  // code = res.code;
});

</script>

<style lang="scss" scoped>
page {
  height: 100%;
}

.login {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 60rpx 60rpx 20rpx;
  box-sizing: border-box;

  .logo {
    flex-direction: flex-start;
    margin-bottom: 40rpx;
    margin-left: 10rpx;
    image {
      width: 110rpx;
      height: 110rpx;
    }
  }

  .txt {
    font-size: 50rpx;
    margin-left: 10rpx;
    color: #333333;
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60%;
    margin-top: 80rpx;
    height: 100rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;
    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .wechat {
    background-color: #ffaa00;
  }

  .extra {
    //flex: 1;
    padding: 70rpx 70rpx 0;
    .caption {
      width: 440rpx;
      line-height: 1;
      font-size: 26rpx;
      color: #999;
      position: relative;
      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .nav{
      display: flex;
      height: 200rpx;
      background-color:#ffffff;
      display: flex;
      flex-wrap: wrap;
    }
    .item{
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .nav .item image{
      height:66rpx;
      width:66rpx;
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }
    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }
}

.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;
}
.link {
  text-decoration: none;
}
::v-deep .is-input-border{
  border:none;
  border-bottom: 2rpx solid #F3F3F3;
  border-radius:0;
}
.policy {
  margin-top: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
.icon {
  margin-top: 8rpx;
  font-size: 30rpx;
  color: #297FD6;
}
::v-deep .van-checkbox__icon--checked {
  background-color: #ffaa00;
  border-color: #ffaa00;
  color: #ffaa00;
}
::v-deep .van-button--default {
  background-color: #fdf3ec !important;
  color: #ffaa00 !important;
  width: 160rpx;
}

.apple_button{
  border-radius: 0.5rem;
  width: 60%;
  background-color: white;
}
.apple_img{
  width: 30rpx;
  height: 40rpx;
  margin-right: 10rpx;
}
.apple_text{

}
</style>